package com.example.wantee;

import java.util.ArrayList;

 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.*;

 
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

 

public class Peticiones extends AsyncTask <Void, Void, JSONArray> {

	private String tipoPeti;
	private String tipoConsult;
	private String parametros;
	private Context contexto;
	private AsyncDelegate delegate;
	
	// Google API Key
    private static final String API_KEY = "AIzaSyC7WVQf2yZmBuv-Og6kLVczMJm67pdL8yA";
    private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
	
	private boolean resultadoVacio = false;
	
	public Peticiones(String tipoPeticion,String tipoConsul, String params, Context cContexto, AsyncDelegate dDelegate) {
		tipoPeti = tipoPeticion;
		parametros = params;
		contexto = cContexto;
		tipoConsult = tipoConsul;
		delegate = dDelegate;
	}
	
    //Antes de empezar con el thread de la peticion
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
	
    
    //Se crea la peticion
    protected JSONArray doInBackground(Void... args) {
        	HttpParams httpParements = new BasicHttpParams();
        	HttpConnectionParams.setConnectionTimeout(httpParements,15000);
        	HttpConnectionParams.setSoTimeout(httpParements, 15000);
        	
        	HttpClient httpclient = new DefaultHttpClient(httpParements);
        	String url = PLACES_SEARCH_URL + parametros + "&key="+API_KEY;
		    Log.i("URL: ", url);

        	HttpPost httppost = new HttpPost(url);
        	try {
    			//httppost.setEntity(new UrlEncodedFormEntity(parameters));
    	    	HttpResponse response = httpclient.execute(httppost);
    	    	int status = response.getStatusLine().getStatusCode();
    	        if(status == 200){
    	        	HttpEntity entity = response.getEntity();
        	    	String result = EntityUtils.toString(entity);
        		    Log.i("Resultado Servidor", result);
          		    JSONObject res = new JSONObject(result);
          		    JSONArray resultado = res.getJSONArray("results");
          		    
          		    String estado = res.getString("status");
          		    if(estado.equalsIgnoreCase("ZERO_RESULTS")){
          			  	resultadoVacio = true;
          		    	Log.i("Resultado Servidor", "Vacio");
          		  	}
          		    
        		    return resultado;   		   
    	        }else{
    	        	Toast.makeText(contexto, "Ha habido algun problema", Toast.LENGTH_LONG).show();
    	    		return null;
    	        }
    	    	
        	} catch (Exception e) {
    			e.printStackTrace();
    		}
    	
		return null;
    	
    }
    
    @Override
    protected void onPostExecute(JSONArray result) {
    	super.onPostExecute(result);
    	
    	GestorListaSitios.getMiListaSitios().parsearResultado(result);
    	
    	if(delegate!=null){
			if(resultadoVacio){
	            delegate.asyncComplete(false);
			}else{
	            delegate.asyncComplete(true);
			}
		}
    	
    	
    	
    }


}
